package com.crl.rcdp.gateway.test;

import com.crl.rcdp.gateway.filter.FilterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.time.Instant;

/**
 * @description:
 * @author: 孔垂云
 * @version: 1.0
 * @date: 2020/7/16 23:26
 */
@Slf4j
//@Service
public class TimeFilter implements GlobalFilter {
    //TODO
    /**
     * token 拦截...
     * 请求开关...
     */

    private final static String GATEWAY_START_TIME = "GATEWAY_START_TIME";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getAttributes().put(GATEWAY_START_TIME, Instant.now().toEpochMilli());
        URI uri = exchange.getRequest().getURI();
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            long startTime = exchange.getAttribute(GATEWAY_START_TIME);
            long endTime = (Instant.now().toEpochMilli() - startTime);
            log.info("请求==>{}{} ,转发时间==>{} ms", FilterUtil.getUriAddress(uri), uri.getPath(), endTime);
        }));
    }

}

